package com.study.view.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.RectF;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.study.view.R;

import java.util.List;

/**
 * author : xujianhong
 * date   : 2023/3/14
 * desc   :
 * version: 1.0
 */
public class TagsView extends ViewGroup{

    private Context mContext;
    /**
     * 设置的行间距
     */
    private int verticalSpacing = 10;

    /**
     * 列间距
     */
    private int horizontalSpacing = 10;

    /**
     * 圆角大小
     */
    private float tag_radius = 10;
    /**
     * 表框粗细大小
     */
    private float tag_border = 3;
    /**
     * 字体大小
     */
    private int textSize = 14;
    /**
     * 标签内边距 顶部
     */
    private int tag_padding_Top = 3;
    /**
     * 标签内边距 底部
     */
    private int tag_padding_Bottom = 3;
    /**
     * 标签内边距 左边
     */
    private int tag_padding_Left = 3;
    /**
     * 标签内边距 右边
     */
    private int tag_padding_Right = 3;

    /**
     * 边框颜色
     */
    private int borderColor = Color.BLUE;

    /**
     * 数据源
     */
    private List<String> tagsList = null;

    public TagsView(Context context) {
        this(context,null);
    }

    public TagsView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public TagsView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        init(attrs);
    }

    private void init(AttributeSet attrs) {

        TypedArray ty = mContext.obtainStyledAttributes(attrs, R.styleable.TagGroup);
        verticalSpacing = (int) ty.getDimension(R.styleable.TagGroup_tag_verticalSpacing,verticalSpacing);
        horizontalSpacing = (int) ty.getDimension(R.styleable.TagGroup_tag_horizontalSpacing,horizontalSpacing);
        tag_radius = ty.getDimension(R.styleable.TagGroup_tag_radius,tag_radius);
        textSize = (int) ty.getDimension(R.styleable.TagGroup_tag_textSize, textSize);
        tag_padding_Top = (int) ty.getDimension(R.styleable.TagGroup_tag_padding_Top,tag_padding_Top);

        tag_padding_Bottom = (int) ty.getDimension(R.styleable.TagGroup_tag_padding_Bottom,tag_padding_Bottom);
        tag_padding_Left = (int) ty.getDimension(R.styleable.TagGroup_tag_padding_Left,tag_padding_Left);
        tag_padding_Right = (int) ty.getDimension(R.styleable.TagGroup_tag_padding_Right,tag_padding_Right);
        borderColor = ty.getColor(R.styleable.TagGroup_tag_border_color,borderColor);
    }

    public void setTagsData(List<String> tags){
        if(tags == null){
            return;
        }
        this.tagsList = tags;
        for (int i = 0; i < tagsList.size(); i++) {
            addView(appendTags(tagsList.get(i)));
        }
    }

    private View appendTags(String tag){
        TextView textView = new TextView(mContext);
        textView.setTextColor(Color.RED);
        textView.setTextSize(textSize);
        textView.setText(tag);
        textView.setPadding(tag_padding_Left,tag_padding_Top,tag_padding_Bottom,tag_padding_Right);
        textView.setBackground(createRoundedDrawable(borderColor, tag_radius, tag_border));
        textView.setOnClickListener(view->{
            //进行操作
            addTag(tag);
        });
        return textView;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        final int heigthMode = MeasureSpec.getMode(heightMeasureSpec);
        final int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        //测量子视图
        measureChildren(widthMeasureSpec, heightMeasureSpec);

        int width = 0;
        int heigth = 0;

        int row = 0;//行数
        int rowWidth = 0;//标记的宽度
        int rowMaxHeight = 0;//标记的高度

        //获取子View的个数
        int count = getChildCount();

        //编辑子view
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            final int childwidth = child.getMeasuredWidth();
            final int childheigth = child.getMeasuredHeight();

            //判断子View是否被不占位隐藏
            if (child.getVisibility() != View.GONE) {
                rowWidth += childwidth;
                //判断单行的宽度是否已经大于组件的宽度，如果已经大于，则换行
                if (rowWidth > widthSize) {
                    rowWidth = childwidth;//下一行的宽度
                    heigth += rowMaxHeight + verticalSpacing;
                    rowMaxHeight = childheigth;//下一行的最大高度
                    row++;//记录行数
                } else {
                    //单行的高度
                    rowMaxHeight =rowMaxHeight +  childheigth;//Math.max(rowMaxHeight, childheigth);
                }
                rowWidth += horizontalSpacing;
            }
        }
        //最后一行的高度
        heigth += rowMaxHeight;
        //最后一行的内间距
        heigth += getPaddingBottom() + getPaddingTop();

        //如果标签只有一行，则就设置宽度包裹标签
        if (row == 0) {
            width += rowWidth;
            width += getPaddingLeft() + getPaddingRight();
        } else {
            //如果标签超过一行，则设置宽度填充父布局
            width = widthSize;
        }
        //设置组件的大小
        setMeasuredDimension(widthMode == MeasureSpec.EXACTLY ? widthSize : width, heigthMode == MeasureSpec.EXACTLY ? heightSize : heigth);

    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        int childCount = getChildCount();

        final int parentLeft = getPaddingLeft();
        final int parentTop = getPaddingTop();
        final int parantRight = r - l - getPaddingRight();
        int childLeft = parentLeft;
        int childTop = parentTop;
        int rowMaxHeight = 0;


        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);

            int width = child.getMeasuredWidth();
            int height = child.getMeasuredHeight();

            if(child.getVisibility() != View.GONE){
                //判断是否需要换行
                if(childLeft + width > parantRight){
                    childLeft = parentLeft;
                    childTop = childTop + rowMaxHeight + verticalSpacing;
                    rowMaxHeight = height;
                } else {
                    rowMaxHeight = Math.max(rowMaxHeight, height);
                }

                child.layout(childLeft, childTop, childLeft + width, childTop + height);

                childLeft = childLeft + width + horizontalSpacing;
            }

        }
    }


    /**
     * 设置圆角边框
     * @param color
     * @param radius
     * @param insetWidth
     * @return
     */
    private ShapeDrawable createRoundedDrawable(int color,float radius,float insetWidth){
        float[] outerRadii = new float[]{radius, radius, radius, radius, radius, radius, radius, radius};
        float[] innerRadii = new float[]{radius, radius, radius, radius, radius, radius, radius, radius};
        RectF rectF = new RectF(insetWidth, insetWidth, insetWidth, insetWidth);
        RoundRectShape roundRectShape = new RoundRectShape(outerRadii, rectF,
       innerRadii);
        ShapeDrawable shapeDrawable = new ShapeDrawable(roundRectShape);
        shapeDrawable.getPaint().setColor(color);
        return shapeDrawable;
    }

    /**
     * 新增
     * @param tag
     */
    public void addTag(String tag){
        if(TextUtils.isEmpty(tag)){
            return;
        }
        removeAllViews();
        tagsList.add(tag);
        setTagsData(tagsList);
        invalidate();
    }

    /**
     * 根据下标进行删除
     * @param tagIndex
     */
    public void deleteTag(int tagIndex){
        tagIndex = tagIndex - 1;
        if (tagIndex > -1 && tagIndex < tagsList.size()) {
            removeViewAt(tagIndex);
            tagsList.remove(tagIndex);
        }
    }
}
